<template>
    <div ref="scrollbarRef"  class="hid">
      <div ref="scrollRef" @scroll="handleScroll" class="scrollbar__wrap">
        <slot></slot>
      </div>
      <div>
        <Bar :ratio-x="ratioX" :ratio-y="ratioY" ref="barRef" :width="sizeWidth" :height="sizeHeight"></Bar>
      </div>
    </div>
</template>

<script setup lang="ts">
import Bar from "./bar.vue"

import {reactive,onMounted,ref, inject, provide, nextTick, computed, onUpdated} from "vue"
import {key} from "./thumb"
import {scrollbarContextKey,GAP} from "./constants"
import type { InjectionKey } from 'vue'
import { react } from "@babel/types"

  let props = defineProps({
    minSize:{
      type:Number,
      default:20
    },
    height:{
      type:Number,
      default:null
    }
  })

  let  scrollRef = ref<HTMLDivElement>()// 内容盒子  
  let scrollbarRef = ref<HTMLDivElement>()//整个容器内容


   // 获取子组件的ref
   let barRef = ref<InstanceType<typeof Bar>|null>(null)
    
    const sizeHeight = ref(0)
    const sizeWidth = ref(0)
    const ratioY = ref(1)
  const ratioX = ref(1)


  // 滚动事件
  let handleScroll = ()=>{
    if(scrollRef.value){
      barRef.value?.handleScroll(scrollRef.value)
    }
  }
 
  const update = ()=>{
    if(scrollRef.value){
    const offsetHeight = scrollRef.value?.offsetHeight -GAP
    const offsetWidth = scrollRef.value.offsetWidth - GAP
  

    const originalHeight = offsetHeight ** 2 / scrollRef.value.scrollHeight
    const originalWidth = offsetWidth ** 2 / scrollRef.value.scrollWidth
    
    const height = Math.max(originalHeight,props.minSize)
    const width = Math.max(originalWidth,props.minSize)
    
    ratioY.value = originalHeight/
    (offsetHeight-originalHeight)/
    (height/(offsetHeight-height))
   // console.log(offsetHeight,offsetWidth)
    ratioX.value = 
    originalWidth/
    (offsetWidth-originalWidth)/
    (width/(offsetWidth-width))

    // 滚动条的高度
    sizeHeight.value =height +GAP <offsetHeight?height:0

    // 滚动条的宽度
    sizeWidth.value = width +GAP<offsetWidth?width:0
      
    // console.log(sizeHeight.value,sizeWidth.value,"sizeHeight")
    // console.log(ratioX.value,ratioY.value)

    }else{
      return
    }
  }

  onUpdated(()=>{
    update()
  })

  provide(scrollbarContextKey,reactive({
    scrollbarElement:scrollbarRef,
    wrapElement:scrollRef
  }))

  // 挂载的时候才能获取dom
  onMounted(()=>{
    nextTick(()=>{
      // initScrollListner()
      update()
      // hei.value = 1000
    })
  
  })



</script>

<style scoped lang="scss">
.hid{
   
    // scrollbar-width: none;
    overflow: hidden;
    position: relative;
    height: 100%;
}
.scrollbar__wrap{
  height: 100%;
  overflow: auto;
  &::-webkit-scrollbar {
        display: none;
      }
}
</style>